package com.duan.laugh.activiti.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duan.laugh.activiti.config.CustomBpmnJsonConverter;
import com.duan.laugh.activiti.config.CustomUserTaskJsonConverter;
import com.duan.laugh.activiti.service.ModelService;
import com.duan.laugh.common.security.util.UserUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.duan.laugh.activiti.constants.ActivitiConstants.*;

/**
 * 工作流模型管理 service实现
 *
 * @author duanjw
 */
@Slf4j
@Service
@AllArgsConstructor
public class ModelServiceImpl implements ModelService {
    private static final String BPMN20_XML = ".bpmn20.xml";
    private final RepositoryService repositoryService;
    private final ObjectMapper objectMapper;
    private final ProcessDiagramGenerator processDiagramGenerator;

    /**
     * 新增模型
     *
     * @param name
     * @param key
     * @param desc
     * @param category
     * @return
     */
    @Override
    public Model insert(String name, String key, String desc, String category) {
        try {
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode properties = objectMapper.createObjectNode();
            properties.put("process_id", key);
            properties.put("name", name);
            editorNode.set("properties", properties);
            ObjectNode stencilset = objectMapper.createObjectNode();
            stencilset.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.set("stencilset", stencilset);

            Model model = repositoryService.newModel();
            model.setKey(key);
            model.setName(name);
            model.setCategory(category);
            model.setVersion(Integer.parseInt(
                    String.valueOf(repositoryService.createModelQuery()
                            .modelKey(model.getKey()).count() + 1)));

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(MODEL_NAME, name);
            modelObjectNode.put(MODEL_REVISION, model.getVersion());
            modelObjectNode.put(MODEL_DESCRIPTION, desc);
            model.setMetaInfo(modelObjectNode.toString());
            model.setTenantId(String.valueOf(UserUtils.getUser().getTenantId()));

            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), editorNode.toString().getBytes("utf-8"));
            return model;
        } catch (UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException", e);
        }
        return null;
    }

    /**
     * 分页查询模型
     *
     * @param params
     * @return
     */
    @Override
    public IPage<Model> selectPage(Map<String, Object> params) {
        ModelQuery modelQuery = repositoryService.createModelQuery()
                .modelTenantId(String.valueOf(UserUtils.getUser().getTenantId())).orderByLastUpdateTime().desc();
        String category = (String) params.get("category");
        if (StrUtil.isNotBlank(category)) {
            modelQuery.modelCategory(category);
        }

        int page = MapUtil.getInt(params, CURRENT);
        int limit = MapUtil.getInt(params, SIZE);

        IPage result = new Page(page, limit);
        result.setTotal(modelQuery.count());
        result.setRecords(modelQuery.listPage((page - 1) * limit, limit));
        return result;
    }

    /**
     * 根据id删除模型
     *
     * @param id
     * @return
     */
    @Override
    public Boolean removeModelById(String id) {
        repositoryService.deleteModel(id);
        return Boolean.TRUE;
    }

    /**
     * 根据id部署模型到流程
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deploy(String id) {
        try {
            // 获取模型
            Model model = repositoryService.getModel(id);
            // 使用自己的解析器
            CustomBpmnJsonConverter.getConvertersToBpmnMap().put("UserTask", CustomUserTaskJsonConverter.class);
            final BpmnModel bpmnModel = convertModelToBpmnModel(model);

            String processName = model.getName();
            if (!StrUtil.endWithIgnoreCase(processName, BPMN20_XML)) {
                processName += BPMN20_XML;
            }
            // 部署流程
            Deployment deployment = repositoryService
                    .createDeployment().name(model.getName())
                    .addBpmnModel(processName, bpmnModel)
                    .tenantId(String.valueOf(UserUtils.getUser().getTenantId()))
                    .deploy();


            // 设置流程分类
            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                    .deploymentId(deployment.getId())
                    .list();

            list.stream().forEach(processDefinition ->
                    repositoryService.setProcessDefinitionCategory(processDefinition.getId(), model.getCategory()));
        } catch (Exception e) {
            log.error("部署失败，异常", e);
        }
        return Boolean.TRUE;
    }

    /**
     * 根据id查看模型图
     * @param id
     * @return
     */
    @Override
    @SneakyThrows
    public InputStream viewById(String id) {
        // 获取模型
        Model model = repositoryService.getModel(id);
        final BpmnModel bpmnModel = convertModelToBpmnModel(model);
        return processDiagramGenerator.generateDiagram(bpmnModel,
                Collections.emptyList(), Collections.emptyList());
    }

    /**
     * 转换model到bpmnModel
     *
     * @param model
     * @return
     */
    @SneakyThrows
    private BpmnModel convertModelToBpmnModel(Model model) {
        // 获取模型
        ObjectNode objectNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(model.getId()));
        return new BpmnJsonConverter().convertToBpmnModel(objectNode);
    }
}
